using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Tulde.WindowsPhone.Music.ViewModel;
using Tulde.WindowsPhone.Music;

namespace MP3tunes.LockerPlayer
{
    public partial class MainPage : PhoneApplicationPage
    {
        private Mp3TunesCredentials credentials;
        private ShellTileUpdateService s = new ShellTileUpdateService();


        // Constructor
        public MainPage()
        {
          
            InitializeComponent();
#if DEBUG
            this.credentials = new Mp3TunesCredentials
            {
                UserName = "demo@mp3tunes.com",
                Password = "demo"
            };
            SecurityProvider.SaveCredentials(this.credentials);
#endif

            // Set the data context of the listbox control to the sample data
            // DataContext = App.ViewModel;

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
          //  this.pivotControl.Items.Remove(this.videos);
           // this.videos.Visibility = System.Windows.Visibility.Collapsed;
            this.ToggleVisibility(true);

        }

        private void ToggleVisibility( bool visible)
        {
            this.pivotControl.Visibility = visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            this.credControl.Visibility = this.pivotControl.Visibility == System.Windows.Visibility.Visible  ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //if( SecurityProvider.IsAuthenticated)
            //{
            //    this.LoadArtists();
            //}
           
        }

        void credControl_Saved(object sender, UserControls.CredentialsEventArgs e)
        {
           
          
            this.ToggleProgressBar(true);
            this.LoadArtists();
            this.ToggleVisibility(true);
            this.credControl.CrossFade(this.pivotControl, OpacityAnimation.Normal, (o, args) =>
               {
                   this.UpdateShellIcon();
                  
               });

                  
          
        }

        


        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.ToggleProgressBar(false);
            this.pivotControl.LoadingPivotItem-=new EventHandler<PivotItemEventArgs>(this.Pivot_LoadingPivotItem);
            
          


            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
              this.credControl.Saved += new EventHandler<UserControls.CredentialsEventArgs>(credControl_Saved);

                this.artistList.SelectionChanged -= new SelectionChangedEventHandler(artistList_SelectionChanged);
               
                if (!SecurityProvider.IsAuthenticated)
                {
                    this.credentials = this.credentials ?? (Mp3TunesCredentials)SecurityProvider.LoadCredentials();
                    if (this.credentials == null)
                    {
                        //this.credControl.FadeIn((x, y) =>
                        //    {
                                //this.pivotControl.Visibility = System.Windows.Visibility.Collapsed;
                                //this.credControl.Visibility = System.Windows.Visibility.Visible;
                       
                            //});
                        this.ToggleVisibility(false);
                        this.pivotControl.CrossFade(this.credControl, OpacityAnimation.Slow, (f, args) => {
                            
                        });
                    }
                    else
                    {
                        this.ToggleVisibility(true);
                        this.ToggleProgressBar(true);
                        this.Authenticate();
                    }
                }
                else
                {
                    this.ToggleVisibility(true);
                    this.ToggleProgressBar(true);
                    this.LoadArtists();
                }
            }
            else
            {
                this.ToggleVisibility(true);
            }
             
        }
        private void UpdateShellIcon()
        {
            if (!SettingsProvider.Settings.EnablePNS && !SettingsProvider.Settings.SuppressEnablePNSDialog)
            {
                MessageBoxResult result = MessageBox.Show(Settings.GetOptInMessage(), "User Action Required", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    SettingsProvider.Settings.EnablePNS = false;
                }
                else if (result == MessageBoxResult.OK)
                {
                    SettingsProvider.Settings.EnablePNS = true;
                    s.GetLatestAlbumArt();
                }
                SettingsProvider.Settings.SuppressEnablePNSDialog = true;
                SettingsProvider.Save();

            }
          
        }
        private void Authenticate()
        {
            MusicServiceFactory.Instance.Authenticate(this.credentials, token =>
            {
                SecurityProvider.SetAuthenticationTokens(token);
                //this.txtShuffle.Visibility = this.shuffle.Visibility = System.Windows.Visibility.Visible;
                this.UpdateShellIcon();

                this.LoadArtists();

                
           
            });
        }

        

        private void Pivot_LoadingPivotItem(object sender, PivotItemEventArgs e)
        {
            this.ToggleProgressBar(true);
            switch (e.Item.Name)
            {
                //case "artists": this.LoadArtists(); break;
                case "albums": this.LoadAlbums(); break;
                case "playlists": this.LoadPlaylists(); break;
                case "videos": this.LoadVideos(); break;
                default: this.ToggleProgressBar(false); break;
            }
        }

        #region Load Pivot Item Methods
        private void LoadArtists()
        {
            this.pivotControl.LoadingPivotItem -= new EventHandler<PivotItemEventArgs>(this.Pivot_LoadingPivotItem);
            this.artistList.SelectionChanged-=new SelectionChangedEventHandler(artistList_SelectionChanged);
            MusicServiceFactory.Instance.EnumerateArtists(list =>
            {
                this.artistList.DataContext = list.Artists;
                this.pivotControl.LoadingPivotItem += new EventHandler<PivotItemEventArgs>(this.Pivot_LoadingPivotItem);
                this.ToggleProgressBar(false);
                this.artistList.SelectionChanged += new SelectionChangedEventHandler(artistList_SelectionChanged);
              
                this.ShowEmptyMessage<Artist>("No Artists Found.",list.Artists);
               
            });
          
        }
        private void LoadAlbums()
        {
            MusicServiceFactory.Instance.EnumerateAlbums(list =>
            {
                this.listAlbums.DataContext = list.Albums;
                this.ToggleProgressBar(false);
                this.ShowEmptyMessage<Album>("No Albums Found.", list.Albums);
                // this.listArtists.DataContext = aristsList.Artists;
                // this.progressBar1.IsIndeterminate = false;
                // this.listArtists.SelectionChanged += new SelectionChangedEventHandler(listArtists_SelectionChanged);

                //this.ToggleShuffleVisibility(!aristsList.Artists.Empty());
            });
        }
        private void LoadPlaylists()
        {
            MusicServiceFactory.Instance.EnumeratePlaylists(list =>
            {

                this.playlistList.DataContext = list.Playlists;
                this.ToggleProgressBar(false);
                this.ShowEmptyMessage<Playlist>("No Playlists Found.", list.Playlists);
                // this.listArtists.DataContext = aristsList.Artists;
                // this.progressBar1.IsIndeterminate = false;
                // this.listArtists.SelectionChanged += new SelectionChangedEventHandler(listArtists_SelectionChanged);

                //this.ToggleShuffleVisibility(!aristsList.Artists.Empty());
            });
        }
        private void LoadVideos()
        {
            //video
            MusicServiceFactory.Instance.EnumerateVideos(list =>
            {

     
                this.ToggleProgressBar(false);
                this.ShowEmptyMessage<Track>("No Videos Found.", list.Tracks);
                // this.listArtists.DataContext = aristsList.Artists;
                // this.progressBar1.IsIndeterminate = false;
                // this.listArtists.SelectionChanged += new SelectionChangedEventHandler(listArtists_SelectionChanged);

                //this.ToggleShuffleVisibility(!aristsList.Artists.Empty());
            });
        }
        #endregion
        private void NavigateToTracks()
        {
            Album album = this.listAlbums.SelectedItem as Album;
            NavigationService.NavigateWithViewModels("/Pages/MediaPlayer.xaml", album);

        }
        private void listAlbums_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
            
                this.NavigateToTracks();
         
        }
        private void artistList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

           
                    Artist artist = this.artistList.SelectedItem as Artist;
                    NavigationService.NavigateWithViewModels("/Pages/AlbumPage.xaml", artist);
              
        
        }

        private void playlistList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
      

          
                Playlist playlist = this.playlistList.SelectedItem as Playlist;
                NavigationService.NavigateWithViewModels("/Pages/MediaPlayer.xaml", playlist);
          
        }

        private void ToggleProgressBar(bool visible)
        {
            this.Dispatcher.BeginInvoke( new Action( ()=>{ this.statusProgress.IsIndeterminate = visible; } ) );
        }

        private void appMenu_OnNavigate(object sender, UserControls.AppMenuEventArg e)
        {
            this.NavigationService.NavigateWithViewModels(e.Destination);
        }

        private void videoList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //Track video = this.videoList.SelectedItem as Track;
            //this.NavigationService.NavigateWithViewModels("/Pages/VideoPlayer.xaml",video);
        }
        private void ShowEmptyMessage<T>(string message, List<T> items)
        {
            if (items.Empty())
            {
                MessageBox.Show(message, "Notification", MessageBoxButton.OK);
            }
        }
    }
}